package com.m4f.fse.components.helpers;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;

public class GaeHttpContentAcquirer {
	
	private int timeout = 1000 * 10; // In milliseconds
	
	public int getTimeout() {
		return this.timeout;
	}
	
	public void setTimeout(int time) {
		this.timeout = time;
	}
	
	
	public byte[] getContent(URI source) throws Exception {
		HttpURLConnection connection = null;
		connection = (HttpURLConnection) source.toURL().openConnection();
		connection.setConnectTimeout(this.timeout); //10 seg.
		connection.setReadTimeout(this.timeout); //10 seg.
		connection.connect();
		byte [] content = null;
		if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
			content = this.getBytesFromInputStream(connection.getInputStream());
		} else {
			throw new Exception("Error stablishing connection, code " + 
					connection.getResponseCode());
		}
		return content;
	}
	
	private byte[] getBytesFromInputStream(InputStream is) throws IOException {
		// Get the size of the file
		long length = is.available();
		if (length > Integer.MAX_VALUE) {
		// File is too large
		}
		// Create the byte array to hold the data
		byte[] bytes = new byte[(int) length];
		// Read in the bytes
		int offset = 0;
		int numRead = 0;
		while (offset < bytes.length
		&& (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
		offset += numRead;
		}
		// Ensure all the bytes have been read in
		if (offset < bytes.length) {
			throw new IOException("Could not completely read file ");
		}
		// Close the input stream and return bytes
		is.close();
		return bytes;
	}

}
